package com.jweb.framework.security.crypto.cipher.asymmetric;

import java.security.KeyStore;
import java.security.PrivateKey;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：JKS格式私钥工厂
 */
public class JksPrivateKeyFactoryBean implements FactoryBean<PrivateKey>, InitializingBean {
	
	protected KeyStore keyStore;
	protected String alias;
	protected String password;
	protected PrivateKey privateKey ;
	
	public PrivateKey getObject() throws Exception {
		return this.privateKey;
	}
	
	public Class<?> getObjectType() {
		return PrivateKey.class;
	}
	
	public boolean isSingleton(){
		return true ;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) this.keyStore.getEntry(this.alias, new KeyStore.PasswordProtection(this.password.toCharArray()));
		
		if(privateKeyEntry == null){
			throw new AsymmetricEncryptionException("no such private key with alias: " + this.alias);
		}
		
		this.privateKey = privateKeyEntry.getPrivateKey();
	}
	
	public void setKeyStore(KeyStore keyStore){
		this.keyStore = keyStore;
	}
	
	public void setAlias(String alias){
		this.alias = alias;
	}
	
	public void setPassword(String password){
		this.password = password;
	}
	
}
